<?php
/**
 * 周舟 hzboye010@163.com
 * addby sublime snippets
 */

namespace app\domain;

use app\src\repair\logic\RepairOrderLogicV2;
use app\src\order\logic\OrdersLogic;
use app\src\seller\emnu\SellerOrderStatusEmnu;
use app\src\seller\helper\OrderCodeHelper;
use app\src\seller\logic\SellerLogic;
use app\src\seller\logic\SellerOrderLogic;
use app\src\wallet\logic\WalletOrderLogicV2;
use app\src\order\logic\OrdersPaycodeLogic;
use app\src\order\model\OrdersPayCode;
use app\src\wxpayApp\service\WxpayServiceApp;

class WxpayDomain extends BaseDomain {

  /**
   * 微信预支付
   */
  public function prePay(){
    $this->checkVersion(100);

    $order_code   = $this->_post('order_code','',Llack('order_code'));

//    $order_info=[
//        'uid' => $this->_post('uid','',Llack('uid')),
//        'amount' => $this->_post('amount','',Llack('amount')),
//        'note' => $this->_post('note',''),
//    ];
//    $seller_id=$this->_post('seller_id','',Llack('seller_id'));
//    $add_order=(new SellerOrderLogic())->addOrder($seller_id,$order_info);
//    $order_code=$add_order['info']['order_code'];

    //商品微信支付

    //? 未支付订单
    $r = (new SellerOrderLogic())->getInfo(['order_code'=>$order_code,'order_status'=>SellerOrderStatusEmnu::UNPAY],false,'uid,seller_id,amount,price');
    if(!$r['status'])     $this->apiReturnErr($r['info']);
    if(empty($r['info'])) $this->apiReturnErr(L('fail').' order_pay_code err : pay_code or pay_status');

    //$order_code     = $r['info']['order_content'];
    //$orderCodeArray = explode(',',$order_code);
    //$tade_no   = $pay_code;

    $seller=(new SellerLogic())->getInfo(['id'=>$r['info']['seller_id']]);
    $seller_name=$seller['info']['name'];
    $orderBody = '购买'.$seller_name.'商品';
    $total_fee = $r['info']['price']; //分
    $r = (new WxpayServiceApp())->getPrePayOrder($orderBody, $order_code, $total_fee);

    $r = $this->parseWxReturn($r);
    $this->exitWhenError($r,true);
  }
  /**
   * 解析维修返回
   * @Author
   * @DateTime 2016-12-22T14:47:50+0800
   * @param    array                    $r [description]
   * @return   [type]                      [description]
   */
  private function parseWxReturn(array $r){
    if($r['return_code'] == 'FAIL'){
      return returnErr(L('fail').' 微信后台 : '.$r['return_msg']);
    }elseif($r['return_code'] == 'SUCCESS'){
      if($r['result_code'] == 'SUCCESS'){
        return returnSuc((new WxpayServiceApp())->reSign($r['prepay_id']));
      }else{
        return returnErr(L('fail').' 微信后台 : '.$r['err_code_des']);
      }
    }else{
      return returnErr(L('fail').' 微信后台 : 返回未知错误');
    }
  }
}